<template>
  <el-dialog title="为用户分配权限" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
    <el-alert v-if="!userId" title="请选择正确的用户" type="error" effect="dark"></el-alert>
    <div style="overflow-x: hidden;">
      <ul v-if="userId" id="treePermissionsForUser" style="height:320px;" class="ztree ztreeMd"></ul>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-tooltip effect="dark" content="重置用户权限后，用户仅拥有所属角色包含的权限，为用户单独指定的权限将无效。" placement="top-start">
        <el-button type="danger" :loading="isSubmitLoading" style="float:left;" @click="resetPermission()">重置</el-button>
      </el-tooltip>
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getUserPermissions, updateUserPermissions, resetAllPermissions } from "@/api/user";
import { getAllPermissions } from "@/api/permisson";
import $ from "@/vendor/jquery";
import "ztree";
import "ztree/css/zTreeStyle/zTreeStyle.css";

export default {
  data() {
    return {
      userId: 0,
      dialogVisible: false,
      isSubmitLoading: false,
      setting: {
        view: {
          showIcon: false
        },
        check: {
          enable: true,
          chkboxType: { Y: "ps", N: "ps" }
        },
        data: {
          simpleData: {
            enable: true
          }
        },
        callback: {
          onClick: this.zTreeOnClick,
          onRightClick: this.zTreeOnRightClick
        }
      }
    };
  },
  methods: {
    show(id) {
      this.userId = id;
      $.fn.zTree.init($("#treePermissionsForUser"), this.setting, []); // 先清空树
      this.dialogVisible = true;
      if (this.userId) {
        const zNodes = [];
        getUserPermissions(this.userId).then(permisssionNames => {
          getAllPermissions().then(result => {
            result.forEach(p => {
              const displayName = p.displayName;
              zNodes.push({
                id: p.name,
                pId: p.parentName,
                name: displayName,
                open: p.isOpen,
                checked: permisssionNames.includes(p.name)
              });
            });
            $.fn.zTree.init($("#treePermissionsForUser"), this.setting, zNodes);
          });
        });
      }
    },
    resetPermission() {
      this.isSubmitLoading = true;
      const input = {
        id: this.userId
      };
      resetAllPermissions(input)
        .then(() => {
          this.$message({ message: "重置成功", type: "success" });
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.close();
        })
        .catch(() => {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
        });
    },
    save() {
      this.isSubmitLoading = true;
      const treeObj = $.fn.zTree.getZTreeObj("treePermissionsForUser");
      const nodes = treeObj.getCheckedNodes(true);
      const input = {
        userId: this.userId,
        permissionNames: nodes.map(item => item.id)
      };
      updateUserPermissions(input)
        .then(() => {
          this.$message({ message: "操作成功", type: "success" });
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.close();
        })
        .catch(() => {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
        });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    },
    zTreeOnClick(event, treeId, treeNode) {
      if (!treeNode) {
        return;
      }
      const treeObj = $.fn.zTree.getZTreeObj(treeId);
      treeObj.expandNode(treeNode);
    },

    zTreeOnRightClick(event, treeId, treeNode) {
      if (!treeNode) {
        return;
      }
      const treeObj = $.fn.zTree.getZTreeObj(treeId);
      treeObj.checkNode(treeNode, !treeNode.checked, true);
    }
  }
};
</script>
